import { Button, message, Popover, Modal, Icon } from 'antd';
import { WeaRichText, WeaLocaleProvider } from 'ecCom';
import * as Util from '../../util/transf';

const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
import { GetUrlParam } from '../../util/Util';
import MoreReplyChild from './MoreReplyChild';
import ReplyItemOps from './ReplyItemOps';

export default class ReplyItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      value: '',
      status: '',
      operate: '',
      editId: '',
      uploadFiles: [],
      uploadImgs: [],
      workFlows: [],
      docs: [],
      richTextUploadStatus: '',
    };
    this.onToolsChange = this.onToolsChange.bind(this);
    this.getBottomBarConfig = this.getBottomBarConfig.bind(this);
  }
  componentDidUpdate() {
    // 图片预览
    $('.wea-doc-detail-reply-list-item img').unbind('click');
    $('.wea-doc-detail-reply-list-item img').bind('click', (event) => {
        if ($(event.target).parent().is('a')) {
          return;
       }
     const imgPool = [];
     let indexNum = 0;
     // clickImgUrl当前点击的图片的来源链接，clickImgId当前点击图片的id
     console.log(event.target.src);

     let clickImgUrl = event.target.src;
     let clickImgId = GetUrlParam(clickImgUrl, 'fileid');
     $('.wea-doc-detail-reply-list-item img').each(function () {
       imgPool.push($(this).attr('src'));
     });
     /** 过滤掉非fileid的图片 */
     let imgShow = imgPool.filter((val) => {
      let fileid = GetUrlParam(val, 'fileid');
      let flag = true;
      if (fileid === '') {
        flag = false;
      }
      return flag;
   });
     for (let i = 0; i < imgShow.length; i++) {
        let imgid = GetUrlParam(imgShow[i], 'fileid');
       if (clickImgId === imgid) {
         break;
       } else {
         indexNum++;
       }
     }
      window.IMCarousel.showImgScanner4Pool(true, imgShow, indexNum, null, window.top);
   });
 }
  onListChange = (ids, list) => {
    this.setState({
      uploadFiles: list,
    });
  }
  getBottomBarConfig() {
    const { uploadFiles, richTextUploadStatus } = this.state;
    let bottomBarConfig = [];
    let datas = this.state.uploadFiles || [];
        datas = datas.map(data => ({
            fileExtendName: data.docextendname,
            fileid: data.id,
            filelink: data.url,
            filename: data.name,
            filesize: data.downName,
            // imgSrc	string	是	附件图标
            loadlink: data.downUrl,
            // showLoad	bool	否	是否可下载
            // showDelete	bool	否	是否可删除
            // isImg	bool	否	非图片模式下是表示文件是否是图片格式
            ...data,
          }));
        bottomBarConfig.push({
          name: 'Upload', // 上传组件
          type: 'list', // 上传组件类型
          show: (
            <div className="wea-doc-detail-upload">
              <div className="rich-button">
                <i className="icon-coms-currency-Enclosure" title={getLabel(128095, ' 上传附件')} />
                {datas.length > 0 && <div className="red-point" />}
                <span className="button-text">{getLabel(517827, ' 附件')}</span>
              </div>
            </div>
          ), // 使用 antd 图标
          uploadUrl: `/api/doc/upload/uploadFile?model=reply&docid=${this.props.docid}`, // 上传地址
          category: '/api/doc/upload/uploadFile?model=reply', // 文档目录
          onListChange: this.onListChange,
          datas,
        });
        return bottomBarConfig;
  }
  onStatusChange = s => this.setState({ status: s })
  onClickUpload = () => {
    let { data, onRichSubmit } = this.props, { operate, editId } = this.state,
    hasMore = 0,
    lastChild = {};
    let DocReplyContent = '';
    if (this.refs && this.refs.comment && this.refs.comment.getData) {
      DocReplyContent = this.refs.comment.getData();
    }
    if (DocReplyContent) {
      let { Upload_image, Upload_file, Browser_152, Browser_37 } = this.state;
      const { uploadFiles, workFlows, docs, uploadImgs } = this.state;
      const fieldAnnexupload = [],
      fieldAnnexuploadName = [],
      signdocids = [],
      signdocnames = [],
      signworkflowids = [],
      signworkflownames = [],
      imgFileids = [],
      imgFilenames = [];
      uploadFiles.forEach((v) => {
        fieldAnnexupload.push(v.fileid);
        fieldAnnexuploadName.push(v.filename);
      });
      docs.forEach((v) => {
        if (DocReplyContent.indexOf(v.id) > -1) {
          signdocids.push(v.id);
          signdocnames.push(v.name);
        }
      });
      workFlows.forEach((v) => {
        if (DocReplyContent.indexOf(v.id) > -1) {
          signworkflowids.push(v.id);
          signworkflownames.push(v.name);
        }
      });
      uploadImgs.forEach((v) => {
        imgFileids.push(v.fileid);
        imgFilenames.push(v.filename);
      });
      typeof onRichSubmit === 'function' && onRichSubmit({
        content: DocReplyContent,
        replyid: (operate === 'edit' || 'save' ? editId : data.replyid),
        operate,
        'field-annexupload': fieldAnnexupload.join(','),
        'field-annexupload-name': fieldAnnexuploadName.join('////~~weaversplit~~////'),
        signdocids: signdocids.join(','),
        signdocnames: signdocnames.join('////~~weaversplit~~////'),
        signworkflowids: signworkflowids.join(','),
        signworkflownames: signworkflownames.join('////~~weaversplit~~////'),
        imgFileids: imgFileids.join(','),
        imgFilenames: imgFilenames.join('////~~weaversplit~~////'),
       },
        hasMore ? { replymainid: lastChild.replymainid, lastreplyid: lastChild.replyid } : 0,
        Upload_image, Upload_file, Browser_152, Browser_37);
      this.setState({ value: '', visible: false, uploadFiles: [], uploadImgs: [], workFlows: [], docs: [] });
      if (this.refs && this.refs.comment && this.refs.comment.setData) {
        // alert(this.refs.comment.setData);

        // this.refs.comment.setData("");
      }
    } else {
      message.warning(getLabel(126383, '回复内容不能为空！'));
    }
  }
  onClickUploadCancel = () => this.setState({ value: '', visible: false, uploadFiles: [], uploadImgs: [], workFlows: [], docs: [] })
  getMoreReplyChild=(params) => {
    const { getMoreReplyChild } = this.props;
    typeof getMoreReplyChild === 'function' && getMoreReplyChild(params);
  }
  render() {
    let { docid, data, extentsConfig, onRichSubmit, isLast, getMoreReplyMain, bottomBarConfig } = this.props,
      { visible, value, status, operate, editId } = this.state,
      hasMore = 0,
      lastChild = {};
    return (
      <div className="wea-doc-detail-reply-list-item" style={data.children.length === 0 && !visible ? { paddingBottom: 0 } : {}}>
        { this.getChild(data, 0, data.children.length > 0) }
        <div className="wea-doc-detail-reply-list-item-children " style={data.children.length === 0 && !visible ? { border: 0 } : {}}>
          {
            data.children.map((child, i) => {
              hasMore = data.children.length === i + 1 && child.ishave;
              if (hasMore) lastChild = child;
              return this.getChild(child, 1);
            })
          }
          {
            visible &&
            <div className="wea-doc-detail-reply-list-item-child cke_editable" style={{ padding: 0, borderTopStyle: 'solid' }}>
              <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@27ci03`}
                id={data.replyid}
                ref="comment"
                // value={value}
                ckConfig={{
                  toolbar: [
                    { name: 'document', items: ['Source'] },
	                  { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'NumberedList', 'BulletedList'] },
	                  { name: 'styles', items: ['Format'] },
	                  { name: 'styles', items: ['Font'] },
	                  { name: 'styles', items: ['FontSize'] },
	                  { name: 'colors', items: ['TextColor'] },
	                  { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
	                  { name: 'links', items: ['Link', 'Unlink'] },
	                  { name: 'insert', items: ['Image', 'Table', 'Smiley'] },
	                  { name: 'tools', items: ['Maximize'] },
                    { name: 'clipboard', items: ['Undo', 'Redo'] },
                  ],
                  height: 100,
                  startupFocus: true,
                  uploadUrl: '/api/doc/upload/uploadFile?model=reply&docid={docid}',
                }}
                extentsConfig={extentsConfig}
                bottomBarConfig={this.getBottomBarConfig()}
                // onChange={v=>this.setState({value: v})}
                onStatusChange={this.onStatusChange}
                onToolsChange={this.onToolsChange}
              />
              {
                status === 'ready' &&
                <div className="wea-doc-detail-reply-rich-btm">
                  <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ss9kle`}
                    type="primary"
                    onClick={this.onClickUpload}
                  >{getLabel(725, '提交')}</Button>
                  <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yun7e8`} type="ghost" style={{ marginLeft: 8 }} 
                    onClick={this.onClickUploadCancel}
                  >{getLabel(31129, '取消')}</Button>
                </div>
              }
            </div>
          }
          {
            hasMore ? <div className="wea-doc-detail-reply-list-item-child cke_editable" style={{ padding: '10px 0', textAlign: 'center' }}>
              {getLabel(126375, '还有{0}条回复，').replace('{0}', lastChild.residue)}
              <MoreReplyChild cbParams={{ replymainid: lastChild.replymainid, lastreplyid: lastChild.replyid }} getMoreReplyChild={this.getMoreReplyChild}>
                {getLabel(82279, '点击查看')}
              </MoreReplyChild>
              <a href="javaScript:void(0)"
            
              ></a>
            </div>
            : null
          }
        </div>
         {
          isLast && data.ishave ? <div style={{ padding: '10px 0', marginTop: 10, textAlign: 'center', border: '1px solid #e8e8e8', borderWidth: '1px 0' }}>
            <MoreReplyChild cbParams={{lastreplyid: data.replyid, orderby: 'desc'}} getMoreReplyChild={this.getMoreReplyChild}>
              {getLabel(82720, '加载更多')}
            </MoreReplyChild>
          </div>
          : null
        }
      </div>
    );
  }
  updateState = (params) => {
    this.setState(params);
  }
  getChild(data, isChild, hasChild = false) {
    const currentUser = window.__currentUser || '';
    let { onPraiseClick, deleteReply } = this.props,
      hasPraise = data.praiseInfo,
      praise = 0,
      isPraise = 0,
      users = [],
      showTime = Util.transfTime(data.rdata, data.rtime),
      userid = data.userid;
    if (hasPraise) {
      praise = hasPraise.users.length;
      isPraise = hasPraise.isPraise;
      users = hasPraise.users;
    }
    return (
      <div className="wea-doc-detail-reply-list-item-child cke_editable" style={data.children ? { border: 0 } : (isChild ? { padding: 10 } : {})}>
        {
          !isChild && <span className="wea-doc-detail-reply-list-item-child-img" dangerouslySetInnerHTML={{ __html: data.handImg }} />
        }
        <div>
          <p className="wea-doc-detail-reply-list-item-child-title">
            <span style={{ marginRight: isChild ? 7 : 12 }} dangerouslySetInnerHTML={{ __html: `<a href='javaScript:openhrm(${data.userid});' onclick='pointerXY(event);' >${data.username}</a>` }} />
            {
              isChild ? <span style={{ marginRight: 4, color: '#484a4d' }}>{getLabel(18540, '回复')}</span> : null
            }
            {
              isChild ? <span dangerouslySetInnerHTML={{ __html: `<a href='javaScript:openhrm(${data.ruserid});' onclick='pointerXY(event);' >${data.rusername}</a>` }} /> : null
            }
            {
              showTime.str.split(' ').length === 2 ? <span>{data.rdata}</span> : null
            }
            {
              showTime.str.split(' ').length === 2 ? <span>{data.rtime}</span> : null
            }
            {
              showTime.str.split(' ').length === 1 ? <span>{showTime.str}</span> : null
            }
          </p>
          <div dangerouslySetInnerHTML={{ __html: data.content }} />
          <div className="wea-doc-detail-reply-list-item-child-extents">
            {
              data.aboutDocs && data.aboutDocs.map((doc, i) => (
                <p style={i === 0 ? {} : { paddingLeft: 20 }}>
                  { i === 0 && <i className="icon-coms-content-o" style={{ marginRight: 8 }} /> }
                  <span dangerouslySetInnerHTML={{ __html: doc.linkUrl }} />
                </p>
              ))
            }
            {
              data.aboutFiles && data.aboutFiles.map((file, i) => (
                <p style={i === 0 ? {} : { paddingLeft: 20 }}>
                  { i === 0 && <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@0kk9xb@${file.linkUrl}`} type="paper-clip" style={{ marginRight: 8 }} /> }
                  <span dangerouslySetInnerHTML={{ __html: file.linkUrl }} />
                </p>
              ))
            }
            {
              data.aboutwfs && data.aboutwfs.map((wf, i) => (
                <p style={i === 0 ? {} : { paddingLeft: 20 }}>
                  { i === 0 && <i className="icon-coms-Workflow-o" style={{ marginRight: 8 }} /> }
                  <span dangerouslySetInnerHTML={{ __html: wf.linkUrl }} />
                </p>
              ))
            }
          </div>
          <ReplyItemOps
            hasChild={hasChild}
            showTime={showTime}
            currentUser={currentUser}
            userid={userid}
            users={users}
            data={data}
            isPraise={isPraise}
            praise={praise}
            updateState={this.updateState}
            deleteReply={deleteReply}
            onPraiseClick={onPraiseClick}
          />
        </div>
      </div>
    );
  }
  onToolsChange(name = '', ids = '', list = [], type = '') {
    let stateList = this.state[`${name}_${type}`],
      mirror = {
        37: 'doc',
        152: 'workflow',
      },
      newList = list.map((item) => {
        let _item = { ...item };
        if (name === 'Upload' && type === 'image') {
          _item.string = `=${_item.fileid}`;
          this.setState({ uploadImgs: list });
        } else if (name === 'Upload' && type === 'file') {
          _item.string = `=${_item.fileid}`;
          this.setState({ uploadFiles: list });
        } else if (name === 'Browser') {
          _item.string = `,${item.id},`;
          type == '37' ? this.setState({ docs: list }) : this.setState({ workFlows: list });
        }
        return _item;
      });
    this.setState({ [`${name}_${type}`]: (stateList ? stateList.concat(newList) : newList) });
    return Util.transfStr(name, ids, list, type);
  }
}
